package van.planifolia.redislock.service;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import van.planifolia.redislock.dao.GoodsDao;
import van.planifolia.redislock.pojo.Goods;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @Author: Van.Planifolia
 * @CreateTime: 2022-12-08  10:21
 * @Version: 1.0
 */
@Service("goodsServiceSp")
public class GoodsServiceSp {
    @Resource
    private GoodsDao goodsDao;
    @Resource
    private RedissonClient redisson;

    public String saleGoods(Integer id) {
        // 我们在进入方法的时候就要获取锁，并且上锁，锁的存活时长为30s
        RLock lock = redisson.getLock("goodsLock::" + id);
        lock.lock(30, TimeUnit.SECONDS);
        try {
            // 判断商品数量是否合格
            Goods goods = goodsDao.selectById(id);
            if (goods.getNub() > 0) {
                goods.setNub(goods.getNub() - 1);
                // 然后更新数据库
                goodsDao.updateById(goods);
                System.out.println("成功卖出一张票,还剩下：" + goods.getNub() + "张");
                return "售卖成功,还剩下" + goods.getNub() + "张";
            }
            System.out.println("票数不足");
            return "售卖失败，票数不足";
            // 无论结果如何要在finally中解锁
        } finally {
            lock.unlock();
        }
    }
}
